﻿/*手机验证码*/
var intervalValidatePhone;
function sendVcode(obj, userPhone, errorMsg, type) {
    if (validatePhoneIsRegist(userPhone, errorMsg)) {//注册，已存在的手机号码弹出错误消息
        if (type == 5) {
            layer.alert(errorMsg);
            return;
        }
    } else {
        if (type == 10) {//重置密码，不存在的手机号码弹出验证消息
            layer.alert(errorMsg);
            return;
        }
    }
    $.ajax({
        url: "/Common/SendVerificationCodeSMS",
        type: "post",
        data: { userPhone: userPhone, verificationCodeTemp: type },
        success: function (data) {
            alert(data.message);
        }
    });
    var date = new Date();
    var ts = date.getTime();//转化为时间戳毫秒数
    date.setTime(ts + 1000 * 60);//设置新时间比旧时间多一分钟
    leftTimer(date, obj, userPhone, errorMsg);
    $("#text").text("重新获取");
    intervalValidatePhone = setInterval(function () {
        leftTimer(date, obj, userPhone, errorMsg);
    }, 1000);
    $(obj).addClass("gray").unbind("click");

}

function leftTimer(date, obj, userPhone, errorMsg) {
    var leftTime = date - (new Date()); //计算剩余的毫秒数
    var seconds = parseInt(leftTime / 1000 % 60, 10); //计算剩余的秒数
    seconds = checkTime(seconds);
    console.log(seconds);
    if (seconds > 0) {
        document.getElementById("timer").innerHTML = "(" + seconds + ")";
    } else {
        clearInterval(intervalValidatePhone);
        document.getElementById("timer").innerHTML = "";
        $(obj).removeClass("gray").click(function () { //发送验证码
            sendVcode(obj, userPhone, errorMsg);
        });
    }
}
function checkTime(i) { //将0-9的数字前面加上0，例1变为01
    if (i < 10 && i > 0) {
        i = "0" + i;
    }
    return i;
}
function validatePhoneIsRegist(phone, errorMsg) {
    var result = false;
    $.ajax({
        url: "/Register/ValidatePhoneIsExist?UserPhone=" + phone,
        type: "post",
        async: false,
        success: function (data) {
            result = data == "True";
            if (data == "False") {
                result = false;
            }
        }
    });
    return result;
}